package com.erp.service.impl;

import com.erp.entity.Perms;
import com.erp.entity.Role;
import com.erp.entity.User;
import com.erp.entity.UserRole;
import com.erp.mapper.RoleMapper;
import com.erp.mapper.UserMapper;
import com.erp.mapper.UserRoleMapper;
import com.erp.service.RolePermsService;
import com.erp.service.UserRoleService;
import com.erp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pyj
 * @since 2020-11-07
 */
@Service
public class UserServiceImpl implements UserService {

    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePermsService rolePermsService;

    @Autowired
    private UserRoleService userRoleService;
    
    @Override
    public List<User> getAll() {
        return userMapper.getAll();
    }

    @Override
    public User findByUserId(String id) {
        return userMapper.findByUserId(id);
    }

    @Override
    public int add(User user) {
        return userMapper.add(user);
    }

    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }

    @Override
    public User findRolesByUserName(String username) {
        return userMapper.findRolesByUserName(username);
    }

    @Override
    public List<Perms> findPermsByRoleId(Integer id) {
        return userMapper.findPermsByRoleId(id);
    }

    @Override
    public int updateHeadPortraits(String username, String headerUrl) {
        return userMapper.updateHeadPortraits(username, headerUrl);
    }

    @Override
    public int update(User user, String roles) {
        // 更新用户拥有的角色,再更新用户信息
        // 删除用户旧的角色,填充新的角色
        String[] res = roles.split(",");
        userRoleMapper.deleteRolesByUserId(user.getId());
        for (String s : res) {
            Role role = roleMapper.findRoleByName(s);
            UserRole userRole = new UserRole();
            userRole.setUid(user.getId());
            userRole.setRid(role.getId());
            userRoleMapper.add(userRole);
        }
        return userMapper.update(user);
    }

    @Override
    public int delete(Integer id) {
        // 删除用户的同时要删除中间角色和权限表信息
        userRoleMapper.deleteRolesByUserId(id);
        return userMapper.delete(id);
    }
}
